package cn.hnu.qq.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.apache.commons.lang.math.RandomUtils;

@Entity
@Table(name="Crowd")
public class Crowd implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private User creater;
	
	private Integer id;
	
	private String crowdName;
	
	private int image = RandomUtils.nextInt(7)+1;;
	
	private Set<User> users = new HashSet<User>();

	@Id @GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(unique=true,nullable=false)
	public String getCrowdName() {
		return crowdName;
	}

	public void setCrowdName(String groupName) {
		this.crowdName = groupName;
	}
	
	@ManyToMany (cascade = {CascadeType.REFRESH,CascadeType.MERGE,CascadeType.PERSIST},fetch=FetchType.EAGER) //产生的user_group表没有主键
    @JoinTable(
                    name="crowd_user",
                    joinColumns = {@JoinColumn(name="user_idcrowd_id",referencedColumnName = "id")},
                    inverseJoinColumns = {@JoinColumn(name="user_id",referencedColumnName = "id")}
                    )
	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}
	
	public void addUser(User user){
		this.users.add(user);
	}

	public void removeUser(User user){
		this.users.remove(user);
	}
	
	@Column(nullable=false)
	public int getImage() {
		return image;
	}

	public void setImage(int image) {
		this.image = image;
	}

	@Override
	public String toString() {
		return crowdName;
	}
	
	@ManyToOne(cascade={CascadeType.MERGE})
	public User getCreater() {
		return creater;
	}

	public void setCreater(User creater) {
		this.creater = creater;
	}

	@Override
	public boolean equals(Object obj) {
		if(obj == null){
			return false;
		}
		if(obj instanceof Crowd){
			Crowd c = (Crowd) obj;
			if(c.getCrowdName().equals(crowdName)){
				return true;
			}
		}
		return false;
	}

//	@Override
//	public String toString() {
//		return "Crowd [id=" + id + ", crowdName=" + crowdName + ", image="
//				+ image + ", users=" + users + "]";
//	}
	
	
}
